import React, { Component } from 'react'

import { SearchBar } from 'antd-mobile'

import { getCurrentCity,API } from '../../../utils'

// import _ from 'lodash'
import debounce from 'lodash/debounce'

import styles from './index.module.css'

export default class Search extends Component {
  // 当前城市id
  // cityId = getCurrentCity().value

  state = {
    // 搜索框的值
    searchTxt: '',
    tipsList: []
  }

  async componentDidMount(){
    const {value} = await getCurrentCity()
    this.cityId = value
  } 
    
  getCommunityList = debounce(async value =>{
    const res = await API.get('/area/community',{
      params:{
         name:value,
         id:this.cityId
      }
    })
    console.log(res);
    this.setState({
      tipsList:res.data.body
    })
  },500)  

  handleChnge=(value)=>{
    this.setState({
      searchTxt:value
    })
    // 调用防抖函数时，传递参数
    this.getCommunityList(value)
  }

 

  // 渲染搜索结果列表
  renderTips = () => {
    const { tipsList } = this.state

    return tipsList.map(item => (
      <li 
        key={item.community} 
        className={styles.tip} 
        onClick={()=>{
          const {community,communityName} = item
          this.props.history.replace('/rent/add',{
            community,
            communityName
          })    
        }}  
      >
        {item.communityName}
      </li>
    ))
  }

  render() {
    const { history } = this.props
    const { searchTxt } = this.state

    return (
      <div className={styles.root}>
        {/* 搜索框 */}
        <SearchBar
          placeholder="请输入小区或地址"
          value={searchTxt}
          onChange={this.handleChnge}
          showCancelButton={true}
          onCancel={() => history.replace('/rent/add')}
        />

        {/* 搜索提示列表 */}
        <ul className={styles.tips}>{this.renderTips()}</ul>
      </div>
    )
  }
}
